<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    class Pages extends CI_Controller
    {
        private $data;
        //funtion initialization
        function __construct()
        {
            parent::__construct();
            //load helper url for using base_url() or site_url()
            //load helper common_function for format money, create alias
            $this->load->helper(array('url','form','common_function'));
            
            //set default seo 
            $this->data['title']='Shop sữa Online | Sữa trên mạng | Sữa cho trẻ sơ sinh ';
            $this->data['meta_keywords']='Shop sữa online, mua sữa trên mạng ở đâu giá tốt, sữa cho trẻ sơ sinh, sữa cho trẻ từ 1 đến 10 tuổi, mua sữa tại hải phòng';
            $this->data['meta_description']='Shop sữa online Chuyên bán: Sữa xách tay giá tốt, sữa cho trẻ sơ sinh, sữa cho trẻ từ 1 đến 10 tuổi, sữa trên mạng giá tốt, giao hàng tận nơi';
            
        }
        
        function home()
        {
            $this->data['page']='home';
            $this->load->model('pages_model');
            $this->data['data']['arr_product_best_seller']=$this->pages_model->get_product_best_seller(9);
            $this->data['data']['arr_product_new']=$this->pages_model->get_product_newest(9);
            $this->load->view('site_master',$this->data);
        }
        
        function list_product($categoryid=null)
        { 
            $this->load->model('pages_model');
            $this->data['data']['title']='Sản phẩm';
            if(isset($categoryid))
            {
                $product_cate=$this->pages_model->get_product_category_by_id($categoryid);
                $this->data['title']=$product_cate['name'];
                $this->data['meta_keywords'] = $product_cate['meta_keywords'];
                $this->data['meta_description']= $product_cate['meta_description'];
                $this->data['data']['title'] = $product_cate['name'];
            }
            $this->data['data']['arr_product']=$this->pages_model->get_product_by_categoryid($categoryid);
            $this->data['page']='list_product';
            $this->load->view('site_master',$this->data);
        }
        
        function introduction()
        {
            $this->data['page']='introduction';
            $this->load->model('pages_model');
            $this->data['data']['content']=$this->pages_model->get_introduction_company();
            $this->load->view('site_master',$this->data);
        }
        
        function product($id=null)
        {
            $this->data['page']='product';
            $this->load->model('pages_model');
            $product=$this->pages_model->get_product_by_id($id);
            if(count($product)>0)
            {
                $this->data['title']=$product['name'];
                $this->data['meta_keywords'] = $product['meta_keywords'];
                $this->data['meta_description']= $product['meta_description'];
            }
            $this->data['data']['item']=$product;
            $this->load->view('site_master',$this->data);
        }
        
        function list_news()
        {
            $this->load->model('pages_model');
            $news_cate=$this->pages_model->get_news_category_by_id(1);//id tin tức
            $this->data['title']=$news_cate['name'];
            $this->data['meta_keywords'] = $news_cate['meta_keywords'];
            $this->data['meta_description']= $news_cate['meta_description'];
            $this->data['data']['title'] = $news_cate['name'];
            $this->data['data']['arr_news']=$this->pages_model->get_news_by_categoryid(1);//id tin tức
            $this->data['page']='list_news';
            $this->load->view('site_master',$this->data);
        }
        
        function news($id)
        {
            $this->data['page']='news';
            $this->load->model('pages_model');
            $news=$this->pages_model->get_news_by_id($id);
            $this->data['title']=$news['title'];
            $this->data['meta_keywords'] = $news['meta_keywords'];
            $this->data['meta_description']= $news['meta_description'];
            $this->data['data']['item']=$news;
            $this->load->view('site_master',$this->data);
        }
        
        function maps()
        {
            $this->data['page']='maps';
            $this->load->view('site_master',$this->data);    
        }
        
        function contact()
        {
            $this->data['page']='contact';
            $this->load->view('site_master',$this->data);
        }
        
        function send_require()
        {
            //validation
            $this->load->library('form_validation');
            $this->form_validation->set_rules('fullname','"Họ tên"','trim|required');
            $this->form_validation->set_rules('phone','"Điện thoại"','trim|required');
            $this->form_validation->set_rules('email','"Email"','trim|required|valid_email');
            $this->form_validation->set_rules('title','"Tiêu đề"','trim|required');
            if($this->form_validation->run()== FALSE)
            {
                $this->contact();
            }
            else
            {
                $record['fullname']=$this->input->post('fullname');
                $record['address']=$this->input->post('address');
                $record['phone']=$this->input->post('phone');
                $record['email']=$this->input->post('email');
                $record['title']=$this->input->post('title');
                $record['content']=$this->input->post('content');
                $record['status']='';
                
                $record['email_receive_require']='support@hoavinh.com';
                
                //config email 'host gmail'
                $email_config = Array(
                    'protocol'  => 'smtp',
                    'smtp_host' => 'ssl://smtp.googlemail.com',
                    'smtp_port' => '465',
                    'smtp_timeout' => '30',
                    'smtp_user' => 'transitionmailhp@gmail.com',
                    'smtp_pass' => 'test1234567',
                    'charset' => 'utf-8',
                    'newline'   => "\r\n",
                    'mailtype'   => "html",  //text/html  Defines email formatting
                );
                $this->load->library('email', $email_config);
     
                $this->email->from('transitionmailhp@gmail.com','Mail Server');
                $this->email->to($record['email_receive_require']);
                $this->email->subject($this->input->post('title'));
                $this->email->message('Thông tin liên hệ từ website bán sữa <br /><br />'.'Họ tên: '.$this->input->post('fullname').'<br />Địa chỉ: '.$this->input->post('address').'<br />Điện thoại: '.$this->input->post('phone').'<br />Email: '.$this->input->post('email').'<br />Nội dung: '.$this->input->post('content'));
                if($this->email->send())
                {
                    $record['status']='send mail success';
                    $this->data['page']='send_mail_success';
                    $this->load->view('site_master',$this->data);
                }
                else
                {
                    $record['status']='send mail error';
                    //show_error($this->email->print_debugger());
                }
                $this->email->clear();
                
                //insert data into database
                $this->load->model('pages_model');
                $this->pages_model->insert_data_to_tblcontact($record);
            }
        }
        
        /*Begin shopping cart*/
        function view_cart()
        {
            $this->data['page']='view_cart';
            $this->load->view('site_master',$this->data);
        }
        
        function order($guest=null)
        {
            $this->load->library('session');
            if($this->session->userdata('sp_cart')==null)
            {
                redirect('home');
            }
            else
            {
                $this->data['page']='order';
                if(isset($guest))
                {
                    $this->data['data']['guest']=$guest;
                }
                $this->load->view('site_master',$this->data);
            }
        }
        
        function order_processing()
        {  
            try
            {
                //echo '<pre>';
                //print_r($_POST);
                $data['email']=$this->input->post('email');
                $data['fullname']=$this->input->post('fullname');
                $data['phone']=$this->input->post('phone');
                $data['address']=$this->input->post('address');
                $data['city']=$this->input->post('city');
                if(array_key_exists('radio',$_POST))
                {
                    $data['payment_form']=$_POST['radio'];
                }
                $data['shipping_form']='Hình thức vận chuyển (Miễn phí trong phạm vi 5 Km (Trong ngày))';
                $data['total_payment']=$this->input->post('total_payment');
                $data['detail_payment']=$this->input->post('detail_payment');
                $data['message_customer']=$this->input->post('message_customer');
                $data['creator']=$this->input->post('email');
                 //formate date
                //note: time slow 5h
                $this->load->helper('date');
                date_default_timezone_set('Asia/Saigon');
                $datestring="%d-%m-%Y %h:%i:%s %A";
                $time=time();
                $format_time=mdate($datestring,$time);
                $data['date_create']=$format_time;
                $data['iscompleted']=0;
                //print_r($data);
                $this->load->model('pages_model');
                $this->pages_model->insert_record_into_table($data,'tblorder');  
                
                redirect('order_success'); 
            }
            catch(Exception $e)
            {
                echo '<script type="text/javascript">alert("'.$e->getMessage().'");</script>';
            }
        }
        
        function order_success()
        {
            $this->data['page']='order_success';
            $this->load->view('site_master',$this->data);
        }
        
        function process_event_cart()
        {
            if(array_key_exists('update_cart',$_POST))
            {
                $this->load->library('session');
                $create_cart['sp_cart']=$this->session->userdata('sp_cart');
                foreach($_POST as $id => $qty)
                {
                    if(array_key_exists($id,$create_cart['sp_cart']))
                    {
                        $quantity = 1;
                        if(is_numeric($qty))
                        {
                            $quantity=$qty;
                        }
                        $create_cart['sp_cart'][$id] = $quantity; 
                    }
                }
                $this->session->set_userdata($create_cart);
                redirect('view_cart');
            }
            else if(array_key_exists('delete_cart',$_POST))
            {
                $this->load->library('session');
                $this->session->unset_userdata('sp_cart');
                redirect('view_cart');
            }
            else if(array_key_exists('order',$_POST))
            {
                redirect('order');
            }
        }
        
        function add_cart($productid,$qty=null)
        {
            $this->load->library('session');
            $quantity = 1;
            if(isset($qty))
            {
                if(is_numeric($qty))
                {
                    $quantity=$qty;
                }
            }
            
            if($this->session->userdata('sp_cart')==null)
            {
                $create_cart['sp_cart'][$productid] = $quantity;
                $this->session->set_userdata($create_cart);           
            }
            else
            {
                if(array_key_exists($productid,$this->session->userdata('sp_cart')))
                {
                    //update item
                    $create_cart['sp_cart']=$this->session->userdata('sp_cart');
                    $create_cart['sp_cart'][$productid] += $quantity; 
                    $this->session->set_userdata($create_cart);
                }
                else
                {
                    //insert item
                    $create_cart['sp_cart']=$this->session->userdata('sp_cart');
                    $create_cart['sp_cart'][$productid] = $quantity; 
                    $this->session->set_userdata($create_cart);
                }
            }
            
            $data['data']=$this->load->view('templates/data_cart_tpl','',true);
            $data['data1']=$this->load->view('templates/section_member_tpl','',true);
            echo json_encode($data);
        }
        
        function remove_item_cart($productid,$page=null)
        {
            $this->load->library('session');
            if(array_key_exists($productid,$this->session->userdata('sp_cart')))
            {
                //remove item
                $create_cart['sp_cart']=$this->session->userdata('sp_cart');
                unset($create_cart['sp_cart'][$productid]);
                $this->session->set_userdata($create_cart);
                
                $data['data']=$this->load->view('templates/data_cart_tpl','',true);
                $data['data1']=$this->load->view('templates/section_member_tpl','',true);
                echo json_encode($data);
            }
            if(isset($page))
            {
                redirect($page);
            }
        }
        /*End shopping cart*/
        
        function form_login($error=null)
        {
            $this->data['page']='form_login';
            if(isset($error))
            {
                $this->data['data']['error']=$error;
            }
            $this->load->view('site_master',$this->data);    
        }
        
        function login()
        {
            if(array_key_exists('login',$_POST))
            {
                $this->load->library('form_validation');
                $config=array(
                            array(
                                'field'=>'email',
                                'label'=>'Email',
                                'rules'=>'trim|required|max_length[100]|xss_clean'
                            ),
                            array(
                                'field'=>'password',
                                'label'=>'Mật khẩu',
                                'rules'=>'trim|required|max_length[50]|xss_clean'
                            )
                );
                $this->form_validation->set_rules($config);
                if($this->form_validation->run()==FALSE)
                {
                    $this->form_login(); 
                }
                else
                {
                    $this->load->database();
                    $this->db->select('email,roles');
                    $this->db->from('tblmembership');
                    $this->db->where('email',$this->input->post('email'));
                    $this->db->where('password',md5($this->input->post('password')));
                    $query=$this->db->get();
                    if($query->num_rows()==0)
                    {
                        $error = 'Tài khoản hoặc mật khẩu không chính xác!';
                        $this->form_login($error);
                    }
                    else if($query->num_rows()==1)
                    {
                        $this->load->library('session');     
                        $this->session->unset_userdata('username');              
                        $user=$query->row_array();
                        //set session
                        $newdata=array(
                                    'email' => $user['email'],
                                    'roles'    => $user['roles'],
                                    'islogged' => TRUE,
                        );
                        $this->session->set_userdata($newdata);
                        
                        redirect('home');
                    }
                }
            }
        }
        
        function logout()
        {
            $this->load->library('session');     
            $this->session->unset_userdata('email'); 
            $this->session->unset_userdata('roles'); 
            $this->session->unset_userdata('islogged');              
            redirect('home');
        }
        
        function test()
        {
            echo '<pre>';
            $this->load->model('pages_model');
            $this->load->library('session');
            //$this->session->sess_destroy();
            //$this->session->unset_userdata('sp_cart');
            echo format_money(180021).'<br />';
            echo format_money(23).'<br />';
            echo format_money(1800243563435).'<br />';
            echo format_money(180).'<br />';
            echo '<br />';
            print_r($this->session->all_userdata());
            echo __FILE__.'<br/>';
            $this->load->view('testeditor');
        }
        
        function newsrss()
        {
            //get content from url container html code
            /*
            $url = "http://dantri.com.vn/xa-hoi/duong-lam-quyen-loi-xa-la-voi-gia-tri-lang-co-733932.htm";
            $str = file_get_contents($url);
            preg_match("/<body[^\>]*>.*<\/body>/m", $str, $matches);
            $str=preg_replace("/<body[^>]*>(.*)/","test",$str);
            echo htmlspecialchars($str);
            echo $matches[2];
            preg_match("~<body.*?>(.*?)<\/body>~is", $str, $match);
            print_r($match);
            */

//            $this->load->library('rssparser');
//            $this->rssparser->set_feed_url('http://dantri.com.vn/trangchu.rss');
//            $this->rssparser->set_cache_life(1);
//            $rss = $this->rssparser->getFeed(10);
//            //insert into database
//            $this->load->model('pages_model');
//            $this->pages_model->insert_array_news($rss);
//            $data['rss'] = $rss;
//            $this->load->view('pages/home',$data);
            
            
            //create catche in time 1 minutes
            //$this->output->cache(1);
            
            //on debug
            //$this->output->enable_profiler(true);
            
            //prevent attack xss
            // if($this->security->xss_clean('sdfdsewt'))
            //{
            //   echo 'safety';
            //}
            //else
            //{
            //    echo 'unsafe';
            //}
            
  //          $ch = curl_init();
//            curl_setopt($ch,CURLINFO_HEADER_OUT,true);
//            curl_setopt($ch, CURLOPT_URL,"http:www.google.com.vn/");
//            curl_setopt($ch, CURLOPT_POST, 0);
//            curl_setopt($ch,CURLOPT_HTTPGET,true);
//            curl_setopt($ch, CURLOPT_USERAGENT, "User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; Tablet PC 2.0)");
//            curl_setopt($ch,CURLOPT_HEADER,TRUE);
//            curl_setopt($ch,CURLOPT_HTTPHEADER,array(
//
//            ));
//            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
//            curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
//            $html=curl_exec ($ch);
//            echo $html;
//            echo curl_getinfo($ch,CURLINFO_HEADER_OUT);
//            curl_close ($ch);
                //$header = array{
                    
                //}
               $this->load->library('http');
               $web = $this->http->Get('http://www.tinhte.vn/threads/the-big-picture-the-gioi-nhin-tu-tren-cao.2108088/','',30,'');
                $this->load->library('simple_html_dom');
                $oDom = new simple_html_dom();
                //$oDom->load($web[0]);
                $oDom=str_get_html($web[0]);
                //$div=$oDom->find('div[class=title fsl fwb fcb]');
                //echo $div->outertext;
                echo $oDom->find('blockquote[class="messageText ugc baseHtml"]',0);
                
                exit;
               $matches;
               
               preg_match('/name="lsd" value="(.{0,15})"/', $web[0], $matches);
               $lsd=$matches[1];
               preg_match('/name="lgnrnd" value="(.{0,15})"/', $web[0], $matches);
               $lgnrnd=$matches[1];
               $lgnjs= $this->parseInt(time()/1000)*1000;
               $post= array(
                            'lsd'=>$lsd,
                            'email'=>'quangphuong_1269@yahoo.com',
                            'pass'=>'anhyeuem',
                            'persistent'=>'1',
                            'default_persistent'=>'0',
                            'timezone'=>'-420',
                            'lgnrnd'=>$lgnrnd,
                            'lgnjs'=>$lgnjs,
                            'locale'=>'vi_VN'

                            );
                $web = $this->http->Post('https://www.facebook.com/login.php?login_attempt=1',$post,'',30,$web[1]);
                $web[0];
//                $this->load->library('simple_html_dom');
//                $oDom = new simple_html_dom();
//                $oDom->load($web[0]);
//                $textFieldValue = $oDom->find('[id="pagelet_bluebar"]',0)->value;
                
//               $str=str_replace('<!DOCTYPE html>','',$web[0]);
//               $str=str_replace('<html lang="en" id="facebook" class="no_js">','<html>',$str);
//               
//             $DOM = new DOMDocument();
////               echo htmlspecialchars($str);
//echo htmlspecialchars($str);
//               $DOM->loadHTML($str);
//                
//                $xpath = new DOMXPath($DOM);
//                $someclass_elements = $xpath->query('$("#pagelet_bluebar").html()');
               //echo $someclass_elements;
               //echo $web[1];
               //echo 'lsd= '.$lsd.' lgnrnd= '.$lgnrnd.' lgnjs= '.$lgnjs;
               //$post= array(
//                'vb_login_username'=>'newhero999',
//                'cookieuser'=>'1',
//                'vb_login_password'=>'',
//                's'=>'',
//                'securitytoken'=>'1369556259-a9f3e0497f781cb59cedc976ef60375da5e624bf',
//                'do'=>'login',
//                'vb_login_md5password'=>'dbb8a8cbc2441837080b40ecce63c13f',
//                'vb_login_md5password_utf'=>'dbb8a8cbc2441837080b40ecce63c13f',
//                            );
//               $web = $this->http->Post('http://4vn.eu/forum/login.php?do=login',$post,'',30,'');
//               $web = $this->http->Get('http://4vn.eu/forum/','',30,$web[1]);
//                echo $web[0];
//               //echo  $this->httpwebrequest->Get('http://www.google.com.vn/','',30);
//               echo '<h2 style="background-color:#d2d2d2;padding:none">'.$web[2].'</h2>';
        }
    }
?>